﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using FrameworkManapro.BusinessModel;
using GMAC.ReportingSystem.Business.Entities;

namespace GMAC.ReportingSystem.DataAccess
{
    public class SecurityDataAccess
    {
        public EntitiesSecurityCollection GetEntities()
        {
            DataSet ds = DataAccessComponent.ExecuteMultipleSelect("procEntitySelect", null);

            EntitiesSecurityCollection result = ReadEntities(ds);
            return result;
        }

        private EntitiesSecurityCollection ReadEntities(DataSet ds)
        {
            if (ds == null || ds.Tables.Count == 0) return null;
            EntitiesSecurityCollection result = new EntitiesSecurityCollection();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                EntitySecurity entity = new EntitySecurity()
                {
                    EntityID = (int)row["EntityID"],
                    EntityName = row["EntityName"].ToString(),
                    DisplayName = row["DisplayName"].ToString()
                };
                result.Add(entity);
            }
            return result;
        }

        public MenuCollection GetMenus()
        {
            DataTable dt = DataAccessComponent.ExecuteSelect("procMenuSelect", null);
            MenuCollection result = ReadMenus(dt);
            return result;
        }

        private MenuCollection ReadMenus(DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0) return null;
            MenuCollection result = new MenuCollection();
            DataView dv = new DataView(dt);
            dv.RowFilter = "MenuParentID Is Null";
            result = ReadMenus(dt, dv);
            return result;
        }

        private void ReadSubMenus(Menu menu, DataTable dt)
        {
            DataView dv = new DataView(dt);
            dv.RowFilter = "MenuParentID = " + menu.MenuId;
            menu.SubMenus = ReadMenus(dt, dv);
        }

        private MenuCollection ReadMenus(DataTable dt, DataView dv)
        {
            if (dv.Count == 0) return null;
            MenuCollection result = new MenuCollection();
            DataRow row;
            for (int i = 0; i < dv.Count; i++)
            {
                row = dv[i].Row;
                Menu menu = new Menu()
                {
                    Action = row["MenuAction"].ToString(),
                    Description = row["MenuDescription"].ToString(),
                    Name = row["MenuName"].ToString(),
                    MenuId = (int)row["MenuID"],
                    URL = row["MenuUrl"].ToString()
                };
                ReadSubMenus(menu, dt);
                result.Add(menu);
            }
            return result;
        }
    }
}
